#! /usr/bin/env python
# coding=utf-8

from tornado.tcpserver import TCPServer
from tornado.ioloop import IOLoop
from aredis import StrictRedis
import config

config = config.Config()


class ConnHandle:
    def __init__(self, **kwargs):
        #TCPServer.__init__(self, **kwargs)
        self.redis_host = config.REDIS_HOST
        self.redis_port = config.REDIS_PORT
        self.cache_name = "future_star"
        self.black_key = "blacklist"
        self.redis_client = StrictRedis(host=self.redis_host, port=self.redis_port)
        self.redis_cache = self.redis_client.cache(self.cache_name)

    async def client_ip_times(self, address):
        ip = address[0]
        ret = await self.redis_cache.get(ip)

        if ret:
            await self.redis_client.incr(ip)
            if ret > 20:
                await self.redis_client.hset(self.black_key, ip, ret)
                return True
            if ret > 10:
                return True
            return False
        else:
            await self.redis_cache.set(ip, 1, expire_time=120)
            return False

    async def black_list(self, address):
        ip = address[0]
        ret = await self.redis_client.hget(self.black_key, ip)
        if ret:
            return True

        return False

#     async def handle_stream(self, stream, address):
#         """
#         测试协程redis
#         :param stream:
#         :param address:
#         :return:
#         """
#         print("A new user has entered the chat room.", address)
#         if await self.black_list(address):
#             print("that is black ip")
#
#         if await self.client_ip_times(address):
#             print("remove the address ip")
#
#
# if __name__ == "__main__":
#     port = 8003
#     print("Server start port:{}......".format(port))
#     server = ConnHandle()
#     server.bind(port)
#     server.start(0)  # Forks multiple sub-processes
#     IOLoop.current().start()
